package api

import (
	"encoding/json"
	"strconv"
	"supershare/backend/controllers"
	"supershare/backend/models"
	"supershare/backend/utils"
	"time"

	"strings"

	"supershare/backend/middleware"

	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/logs"
	"github.com/beego/beego/v2/server/web"
)

// VenueController 小程序场地控制器
type VenueController struct {
	web.Controller
}

// VenueDetailResponse 场地详情响应
type VenueDetailResponse struct {
	Id               int64                  `json:"id"`
	Name             string                 `json:"name"`
	StoreName        string                 `json:"store_name"` // 门店名称
	StoreId          int64                  `json:"store_id"`
	StoreAddress     string                 `json:"store_address"` // 门店地址
	Phone            string                 `json:"phone"`         // 门店客服电话
	Capacity         int                    `json:"capacity"`
	Area             float64                `json:"area"`
	HourPrice        float64                `json:"hour_price"`
	DayPrice         float64                `json:"day_price"`
	TimeBasedPricing string                 `json:"time_based_pricing"` // 分时段定价
	Description      string                 `json:"description"`
	SpecialNotice    string                 `json:"special_notice"`
	Facilities       string                 `json:"facilities"`
	Images           string                 `json:"images"`
	VenueType        string                 `json:"venue_type"`
	StatusText       string                 `json:"status_text"`
	StatusColor      string                 `json:"status_color"` // 状态颜色
	StartTime        string                 `json:"start_time"`   // 开始预约时间
	OpeningHours     string                 `json:"opening_hours"`
	Packages         []*models.VenuePackage `json:"packages"`
}

// VenuePackageResponse 场地套餐响应
type VenuePackageResponse struct {
	Id                int64   `json:"id"`                 // 套餐ID
	Name              string  `json:"name"`               // 套餐名称
	Description       string  `json:"description"`        // 套餐描述
	Price             float64 `json:"price"`              // 套餐价格
	Hours             int     `json:"hours"`              // 使用时长(小时)
	StoreId           int64   `json:"store_id"`           // 所属门店ID
	StoreName         string  `json:"store_name"`         // 所属门店名称
	AvailableTimes    string  `json:"available_times"`    // 可用时段
	AvailableWeekdays string  `json:"available_weekdays"` // 可用星期
}

// Detail 获取场地详情
func (c *VenueController) Detail() {
	// 获取场地ID
	idStr := c.GetString("id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil || id <= 0 {
		c.Data["json"] = controllers.ErrorResponse("无效的场地ID")
		c.ServeJSON()
		return
	}

	// 获取场地信息
	venue, err := models.GetVenueById(id)
	if err != nil {
		c.Data["json"] = controllers.ErrorResponse("场地不存在")
		c.ServeJSON()
		return
	}

	// 获取门店信息
	store, err := models.GetStoreById(venue.StoreId)
	if err != nil {
		c.Data["json"] = controllers.ErrorResponse("获取门店信息失败")
		c.ServeJSON()
		return
	}

	// 获取当前会员信息（如果已登录）
	member, _ := middleware.GetCurrentMember(c.Ctx)

	// 加盟商权限验证 - 会员如果已登录，只能查看自己加盟商的场地
	if member != nil && member.FranchiseId > 0 && venue.FranchiseId != member.FranchiseId {
		c.Data["json"] = controllers.ErrorResponse("无权查看该场地")
		c.ServeJSON()
		return
	}

	// 获取场地套餐
	packages, err := models.GetVenuePackagesByVenueId(id)
	if err != nil {
		c.Data["json"] = controllers.ErrorResponse("获取场地套餐失败")
		c.ServeJSON()
		return
	}
	// 基础URL
	baseURL := web.AppConfig.DefaultString("imghost", "http://127.0.0.1:8888")
	// 处理场地图片
	var imageUrls []string
	var imageUrl string
	if venue.Images != "" {
		utils.UnmarshalJSON(venue.Images, &imageUrls)
		for _, url := range imageUrls {
			if len(url) > 0 && url[0] == '/' {
				imageUrl = baseURL + strings.ReplaceAll(url, "\\", "/")
				break
			}
		}
	}
	startTime := time.Now().Format("15:04")
	statusText := "空闲中"
	statusColor := "#4CAF50" // 绿色
	now := time.Now().Unix()
	order, _ := models.GetFirstUpcomingOrActiveOrder(venue.Id, now)

	if order != nil {
		if now >= order.StartTime {
			// 正在进行中
			// 获取保洁预留时间
			cleaningSetting, err := models.GetCleaningSettingByStoreId(venue.StoreId)
			reservedMinutes := 15 // 默认15分钟
			if err == nil && cleaningSetting.Enabled {
				reservedMinutes = cleaningSetting.ReservedMinutes
			}
			startTime = time.Unix(order.EndTime+int64(reservedMinutes*60), 0).Format("15:04")
			statusText = time.Unix(order.EndTime, 0).Format("15:04") + " 结束"
			statusColor = "#FF9800" // 橙色
		} else {
			// 即将开始
			statusText = time.Unix(order.StartTime, 0).Format("15:04") + " 开始"
			statusColor = "#2196F3" // 蓝色
		}
	} else { // 如果没有订单，则根据场地的通用状态显示
		switch venue.Status {
		case 1:
			statusText = "空闲中"
			statusColor = "#4CAF50" // 绿色
		case 2:
			statusText = "使用中"
			statusColor = "#FF9800" // 橙色
		case 3:
			statusText = "保洁中"
			statusColor = "#2196F3" // 蓝色
		case 4:
			statusText = "待保洁"
			statusColor = "#FFC107" // 黄色
		case 5:
			statusText = "维护中"
			statusColor = "#F44336" // 红色
		case 6:
			statusText = "装修中"
			statusColor = "#9C27B0" // 紫色
		}
	}

	// 构建响应数据
	response := &VenueDetailResponse{
		Id:               venue.Id,
		Name:             venue.Name,
		StoreName:        store.Name,
		StoreId:          venue.StoreId,
		StoreAddress:     store.Address,
		Phone:            store.Phone,
		Capacity:         venue.Capacity,
		Area:             venue.Area,
		HourPrice:        venue.HourPrice,
		DayPrice:         venue.DayPrice,
		TimeBasedPricing: venue.TimeBasedPricing,
		Description:      venue.Description,
		SpecialNotice:    venue.SpecialNotice,
		Facilities:       venue.Facilities,
		Images:           imageUrl,
		VenueType:        venue.VenueType,
		OpeningHours:     venue.OpeningHours,
		StatusText:       statusText,
		StartTime:        startTime,
		StatusColor:      statusColor,
		Packages:         packages,
	}

	// 返回成功响应
	c.Data["json"] = controllers.SuccessResponse(response)
	c.ServeJSON()
}

// Packages 获取场地套餐
func (c *VenueController) Packages() {
	// 获取场地ID
	idStr := c.GetString("id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil || id <= 0 {
		c.Data["json"] = controllers.ErrorResponse("无效的场地ID")
		c.ServeJSON()
		return
	}

	// 获取场地信息
	venue, err := models.GetVenueById(id)
	if err != nil {
		c.Data["json"] = controllers.ErrorResponse("场地不存在")
		c.ServeJSON()
		return
	}

	// 获取门店信息
	store, err := models.GetStoreById(venue.StoreId)
	if err != nil {
		c.Data["json"] = controllers.ErrorResponse("获取门店信息失败")
		c.ServeJSON()
		return
	}

	// 获取场地套餐
	packages, err := models.GetVenuePackagesByVenueId(id)
	if err != nil {
		c.Data["json"] = controllers.ErrorResponse("获取场地套餐失败")
		c.ServeJSON()
		return
	}

	// 转换为前端需要的格式
	packageList := make([]*VenuePackageResponse, 0)
	for _, pkg := range packages {
		packageList = append(packageList, &VenuePackageResponse{
			Id:                pkg.Id,
			Name:              pkg.Name,
			Description:       pkg.Description,
			Price:             pkg.Price,
			Hours:             pkg.Duration, // 使用Duration字段作为Hours
			AvailableTimes:    pkg.AvailableTimes,
			AvailableWeekdays: pkg.AvailableWeekdays,
			StoreId:           venue.StoreId,
			StoreName:         store.Name,
		})
	}

	// 返回成功响应
	c.Data["json"] = controllers.SuccessResponse(map[string]interface{}{
		"list": packageList,
	})
	c.ServeJSON()
}

// TimeSlots 获取可预约时间段
func (c *VenueController) TimeSlots() {
	// 获取查询参数
	id, _ := c.GetInt64("id", 0)
	dateStr := c.GetString("date", "")

	// 验证参数
	if id <= 0 {
		c.Data["json"] = controllers.ErrorResponse("场地ID不能为空")
		c.ServeJSON()
		return
	}

	// 如果日期为空，使用当前日期
	if dateStr == "" {
		now := time.Now()
		dateStr = now.Format("2006-01-02")
	}

	// 查询场地信息
	_, err := models.GetVenueById(id)
	if err != nil {
		c.Data["json"] = controllers.ErrorResponse("场地不存在")
		c.ServeJSON()
		return
	}

	// 查询订单
	date, _ := time.Parse("2006-01-02", dateStr)
	startOfDay := time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, time.Local)
	endOfDay := startOfDay.Add(24 * time.Hour)

	// 查询数据库中是否有重叠的预约
	o := orm.NewOrm()
	var bookings []*models.Order
	_, err = o.QueryTable(new(models.Order)).
		Filter("venue_id", id).
		Filter("status__in", 0, 1, 2). // 待确认或已确认的订单
		Filter("is_deleted", 0).
		Filter("start_time__lt", endOfDay.Unix()). // 开始时间小于结束时间
		Filter("end_time__gt", startOfDay.Unix()). // 结束时间大于开始时间
		All(&bookings)

	if err != nil {
		c.Data["json"] = controllers.ErrorResponse("获取预约信息失败")
		c.ServeJSON()
		return
	}

	// 构建时间段
	timeSlots := make([]map[string]interface{}, 0)
	for hour := 0; hour < 24; hour++ {
		isAvailable := true
		for _, booking := range bookings {
			// 检查是否有预约覆盖当前小时
			startHour := time.Unix(booking.StartTime, 0).Hour()
			endHour := time.Unix(booking.EndTime, 0).Hour()

			// 如果结束时间是0点，表示24点
			if endHour == 0 {
				endHour = 24
			}

			// 如果当前小时在预约时间范围内，则标记为不可用
			if hour >= startHour && hour < endHour {
				isAvailable = false
				break
			}
		}

		timeSlots = append(timeSlots, map[string]interface{}{
			"hour":         hour,
			"is_available": isAvailable,
		})
	}

	// 返回结果
	c.Data["json"] = controllers.SuccessResponse(map[string]interface{}{
		"venue_id":   id,
		"date":       dateStr,
		"time_slots": timeSlots,
	})
	c.ServeJSON()
}

// Timeline 获取房间时间轴数据
func (c *VenueController) Timeline() {
	// 获取查询参数
	roomId, _ := c.GetInt64("room_id", 0)
	dateStr := c.GetString("date", "")

	// 验证参数
	if roomId <= 0 {
		c.Data["json"] = controllers.ErrorResponse("房间ID不能为空")
		c.ServeJSON()
		return
	}

	// 如果日期为空，使用当前日期
	if dateStr == "" {
		now := time.Now()
		dateStr = now.Format("2006-01-02")
	}

	// 查询房间信息
	_, err := models.GetVenueById(roomId)
	if err != nil {
		c.Data["json"] = controllers.ErrorResponse("房间不存在")
		c.ServeJSON()
		return
	}

	// 查询订单
	date, _ := time.Parse("2006-01-02", dateStr)
	startOfDay := time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, time.Local)
	endOfDay := startOfDay.Add(24 * time.Hour)

	// 查询数据库中是否有重叠的预约
	o := orm.NewOrm()
	var bookings []*models.Order
	_, err = o.QueryTable(new(models.Order)).
		Filter("venue_id", roomId).
		Filter("status__in", 0, 1, 2). // 待确认或已确认的订单
		Filter("is_deleted", 0).
		Filter("start_time__lt", endOfDay.Unix()). // 开始时间小于结束时间
		Filter("end_time__gt", startOfDay.Unix()). // 结束时间大于开始时间
		All(&bookings)

	if err != nil {
		c.Data["json"] = controllers.ErrorResponse("获取预约信息失败")
		c.ServeJSON()
		return
	}

	// 构建时间槽数据
	slots := make([]map[string]interface{}, 0)
	for hour := 0; hour < 24; hour++ {
		isBooked := false
		// 检查该小时是否已被预约
		for _, booking := range bookings {
			// 获取预约的开始和结束小时
			startHour := time.Unix(booking.StartTime, 0).Hour()
			endHour := time.Unix(booking.EndTime, 0).Hour()

			// 如果结束时间是0点，表示24点
			if endHour == 0 {
				endHour = 24
			}

			// 如果当前小时在预约时间范围内，则标记为已预约
			if hour >= startHour && hour < endHour {
				isBooked = true
				break
			}
		}

		slots = append(slots, map[string]interface{}{
			"hour":     hour,
			"isBooked": isBooked,
		})
	}

	// 返回结果
	c.Data["json"] = controllers.SuccessResponse(map[string]interface{}{
		"room_id": roomId,
		"date":    dateStr,
		"slots":   slots,
	})
	c.ServeJSON()
}

// VenueTimelineResponse 场地时间线响应结构体
type VenueTimelineResponse struct {
	models.Venue
	Orders []*models.Order `json:"orders"`
}

// TimelineList 为时间线视图获取场地列表和未来24小时的订单
func (c *VenueController) TimelineList() {
	// 获取请求参数
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("pageSize", 10)
	venueType := c.GetString("venue_type")
	storeId, _ := c.GetInt64("store_id", 0)

	// 构建过滤条件
	filters := make(map[string]interface{})
	if venueType != "" {
		filters["venue_type"] = venueType
	}
	if storeId > 0 {
		filters["store_id"] = storeId
	}

	// 获取当前会员信息（如果已登录）
	member, _ := middleware.GetCurrentMember(c.Ctx)

	// 加盟商权限过滤
	if member != nil && member.FranchiseId > 0 {
		filters["franchise_id"] = member.FranchiseId
	}

	// 查询场地列表
	venues, total, err := models.GetVenueList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = controllers.ErrorResponse("获取场地列表失败")
		c.ServeJSON()
		return
	}

	// 为每个场地获取未来24小时的订单
	now := time.Now()
	twentyFourHoursLater := now.Add(24 * time.Hour)

	var responseList []VenueTimelineResponse
	for _, venue := range venues {
		orders, err := models.GetOrdersForVenueBetween(venue.Id, now.Unix(), twentyFourHoursLater.Unix())
		if err != nil {
			logs.Error("Failed to get orders for venue %d: %v", venue.Id, err)
			// 即使获取订单失败，也继续处理下一个场地
			orders = []*models.Order{} // 返回空数组
		}

		responseList = append(responseList, VenueTimelineResponse{
			Venue:  *venue,
			Orders: orders,
		})
	}

	// 返回结果
	c.Data["json"] = controllers.SuccessResponse(map[string]interface{}{
		"list":  responseList,
		"total": total,
	})
	c.ServeJSON()
}

// List 获取场地列表
func (c *VenueController) List() {
	// 获取请求参数
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("pageSize", 10)
	venueType := c.GetString("venue_type")
	storeId, _ := c.GetInt64("store_id", 0)
	minCapacity, _ := c.GetInt("min_capacity", 0)
	maxCapacity, _ := c.GetInt("max_capacity", 0)

	// 构建过滤条件
	filters := make(map[string]interface{})
	if venueType != "" {
		filters["venue_type"] = venueType
	}
	if storeId > 0 {
		filters["store_id"] = storeId
	}
	if minCapacity > 0 {
		filters["min_capacity"] = minCapacity
	}
	if maxCapacity > 0 {
		filters["max_capacity"] = maxCapacity
	}
	// 只获取状态为空闲的场地
	filters["status"] = int8(1)

	// 获取当前会员信息（如果已登录）
	member, _ := middleware.GetCurrentMember(c.Ctx)

	// 加盟商权限过滤 - 会员如果已登录，只能查看自己加盟商的场地
	if member != nil && member.FranchiseId > 0 {
		filters["franchise_id"] = member.FranchiseId
	}

	// 查询场地列表
	venues, total, err := models.GetVenueList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = controllers.ErrorResponse("获取场地列表失败")
		c.ServeJSON()
		return
	}

	// 为每个场地添加门店名称和订单信息
	type VenueWithDetails struct {
		*models.Venue
		StoreName   string         `json:"store_name"`
		StatusText  string         `json:"status_text"`
		StatusColor string         `json:"status_color"`
		Orders      []models.Order `json:"orders"`
	}

	venueList := make([]*VenueWithDetails, 0)
	storeIds := make(map[int64]bool)
	for _, venue := range venues {
		storeIds[venue.StoreId] = true
	}

	// 获取所有门店信息
	storeMap := make(map[int64]*models.Store)
	for storeId := range storeIds {
		store, err := models.GetStoreById(storeId)
		if err == nil {
			storeMap[storeId] = store
		}
	}

	// 组装返回数据
	for _, venue := range venues {
		storeName := ""
		if store, ok := storeMap[venue.StoreId]; ok {
			storeName = store.Name
		}
		statusText := "空闲中"
		statusColor := "#4CAF50" // 绿色
		now := time.Now()
		order, _ := models.GetFirstUpcomingOrActiveOrder(venue.Id, now.Unix())

		if order != nil {
			if now.Unix() >= order.StartTime {
				cleaningSetting, err := models.GetCleaningSettingByStoreId(venue.StoreId)
				reservedMinutes := 15 // 默认15分钟
				if err == nil && cleaningSetting.Enabled {
					reservedMinutes = cleaningSetting.ReservedMinutes
				}
				statusText = time.Unix(order.EndTime+int64(reservedMinutes)*60, 0).Format("15:04") + " 结束"
				statusColor = "#FF9800" // 橙色
			} else {
				statusText = time.Unix(order.StartTime, 0).Format("15:04") + " 开始"
				statusColor = "#2196F3" // 蓝色
			}
		} else { // 如果没有订单，则根据场地的通用状态显示
			switch venue.Status {
			case 1:
				statusText = "空闲中"
				statusColor = "#4CAF50" // 绿色
			case 2:
				statusText = "使用中"
				statusColor = "#FF9800" // 橙色
			case 3:
				statusText = "保洁中"
				statusColor = "#2196F3" // 蓝色
			case 4:
				statusText = "待保洁"
				statusColor = "#FFC107" // 黄色
			case 5:
				statusText = "维护中"
				statusColor = "#F44336" // 红色
			case 6:
				statusText = "装修中"
				statusColor = "#9C27B0" // 紫色
			}
		}

		// 获取未来24小时的订单
		future := now.Add(24 * time.Hour)
		var orders []models.Order
		o := orm.NewOrm()
		o.QueryTable(new(models.Order)).Filter("venue_id", venue.Id).Filter("start_time__lt", future.Unix()).Filter("end_time__gt", now.Unix()).Filter("status__in", 1, 2).All(&orders)

		venueList = append(venueList, &VenueWithDetails{
			Venue:       venue,
			StoreName:   storeName,
			StatusText:  statusText,
			StatusColor: statusColor,
			Orders:      orders,
		})
	}

	// 返回成功响应
	c.Data["json"] = controllers.SuccessResponse(map[string]interface{}{
		"list":  venueList,
		"total": total,
		"page":  page,
		"size":  pageSize,
	})
	c.ServeJSON()
}

// CheckAvailable 检查时间段是否可用
func (c *VenueController) CheckAvailable() {
	// 获取场地ID
	venueId, _ := c.GetInt64("venue_id", 0)
	if venueId <= 0 {
		c.Data["json"] = controllers.ErrorResponse("无效的场地ID")
		c.ServeJSON()
		return
	}

	// 获取开始和结束时间
	startTimeStr := c.GetString("start_time")
	endTimeStr := c.GetString("end_time")
	if startTimeStr == "" || endTimeStr == "" {
		c.Data["json"] = controllers.ErrorResponse("请提供开始和结束时间")
		c.ServeJSON()
		return
	}

	startTime, err := strconv.ParseInt(startTimeStr, 10, 64)
	if err != nil {
		c.Data["json"] = controllers.ErrorResponse("开始时间格式错误")
		c.ServeJSON()
		return
	}

	endTime, err := strconv.ParseInt(endTimeStr, 10, 64)
	if err != nil {
		c.Data["json"] = controllers.ErrorResponse("结束时间格式错误")
		c.ServeJSON()
		return
	}

	// 检查时间是否合理
	if startTime >= endTime {
		c.Data["json"] = controllers.ErrorResponse("开始时间必须早于结束时间")
		c.ServeJSON()
		return
	}

	// 获取场地信息
	venue, err := models.GetVenueById(venueId)
	if err != nil {
		c.Data["json"] = controllers.ErrorResponse("场地不存在")
		c.ServeJSON()
		return
	}

	// 检查场地状态
	if venue.Status != 1 {
		c.Data["json"] = controllers.ErrorResponse("该场地当前不可预约")
		c.ServeJSON()
		return
	}

	// 查询数据库中是否有重叠的预约
	o := orm.NewOrm()
	count, err := o.QueryTable(new(models.Order)).
		Filter("venue_id", venueId).
		Filter("status__in", 0, 1). // 待确认或已确认的订单
		Filter("is_deleted", 0).
		Filter("start_time__lt", endTime). // 开始时间小于请求的结束时间
		Filter("end_time__gt", startTime). // 结束时间大于请求的开始时间
		Count()

	if err != nil {
		c.Data["json"] = controllers.ErrorResponse("系统错误，请稍后再试")
		c.ServeJSON()
		return
	}

	if count > 0 {
		c.Data["json"] = controllers.ErrorResponse("该时间段已被预约")
		c.ServeJSON()
		return
	}

	// 获取门店信息以检查营业时间
	store, err := models.GetStoreById(venue.StoreId)
	if err != nil {
		c.Data["json"] = controllers.ErrorResponse("获取门店信息失败")
		c.ServeJSON()
		return
	}

	// 定义营业时间的数据结构
	type DailySchedule struct {
		Day       int    `json:"day"`
		DayName   string `json:"dayName"`
		IsOpen    bool   `json:"isOpen"`
		OpenTime  string `json:"openTime"`
		CloseTime string `json:"closeTime"`
	}
	type BusinessHours struct {
		Workday DailySchedule   `json:"workday"`
		Weekend DailySchedule   `json:"weekend"`
		Daily   []DailySchedule `json:"daily"`
	}

	var businessHours BusinessHours
	if err := json.Unmarshal([]byte(store.BusinessHours), &businessHours); err == nil {
		// 检查预约时间是否在营业时间内
		startDateTime := time.Unix(startTime, 0)
		endDateTime := time.Unix(endTime, 0)
		weekday := startDateTime.Weekday()

		var schedule DailySchedule
		// Go的Weekday, Sunday是0, Monday是1, ..., Saturday是6
		// 我们系统的day, 1是周一, ..., 7是周日
		dayOfWeek := int(weekday)
		if dayOfWeek == 0 { // Sunday
			dayOfWeek = 7
		}

		// 优先使用daily的配置
		foundDaily := false
		for _, s := range businessHours.Daily {
			if s.Day == dayOfWeek {
				schedule = s
				foundDaily = true
				break
			}
		}

		// 如果daily没有配置，则根据工作日和周末来判断
		if !foundDaily {
			if weekday >= time.Monday && weekday <= time.Friday {
				schedule = businessHours.Workday
			} else {
				schedule = businessHours.Weekend
			}
		}

		if !schedule.IsOpen {
			c.Data["json"] = controllers.ErrorResponse("预约当天门店不营业")
			c.ServeJSON()
			return
		}

		openingTime, errOpen := time.Parse("15:04", schedule.OpenTime)
		closingTime, errClose := time.Parse("15:04", schedule.CloseTime)

		if errOpen != nil || errClose != nil {
			c.Data["json"] = controllers.ErrorResponse("门店营业时间格式配置错误")
			c.ServeJSON()
			return
		}

		year, month, day := startDateTime.Date()
		openingTime = time.Date(year, month, day, openingTime.Hour(), openingTime.Minute(), 0, 0, startDateTime.Location())
		closingTime = time.Date(year, month, day, closingTime.Hour(), closingTime.Minute(), 0, 0, startDateTime.Location())

		if startDateTime.Before(openingTime) || endDateTime.After(closingTime) {
			c.Data["json"] = controllers.ErrorResponse("预约时间不在营业时间内")
			c.ServeJSON()
			return
		}
	} else {
		logs.Error("解析门店营业时间失败: %v, 营业时间: %s", err, store.BusinessHours)
	}

	// 返回可用结果
	c.Data["json"] = controllers.SuccessResponse(map[string]interface{}{
		"available":  true,
		"venue_id":   venueId,
		"venue_name": venue.Name,
	})
	c.ServeJSON()
}
